document.addEventListener('DOMContentLoaded', function() {
    // 获取页面元素
    const saveBtn = document.getElementById('saveBtn');
    const profileForm = document.getElementById('profileForm');
    const passwordInputs = document.querySelectorAll('input[type="password"]');
    const editableFields = document.querySelectorAll('input:not([id="title"], [id="hire_date"])');
    const toggleCurrent = document.getElementById('toggleCurrentPassword');
    const toggleNew = document.getElementById('toggleNewPassword');
    const toggleConfirm = document.getElementById('toggleConfirmPassword');

    // 初始化可编辑字段和密码切换
    editableFields.forEach(field => field.disabled = false);
    initPasswordToggle(toggleCurrent, 'current_password');
    initPasswordToggle(toggleNew, 'new_password');
    initPasswordToggle(toggleConfirm, 'confirm_password');

    // 保存按钮点击事件
    saveBtn.addEventListener('click', function() {
        const errors = [];
        const email = document.getElementById('email').value;
        const telephone = document.getElementById('telephone').value;
        const currentPass = document.getElementById('current_password').value;
        const newPass = document.getElementById('new_password').value;
        const confirmPass = document.getElementById('confirm_password').value;

        // 前端验证
        if (email && !isValidEmail(email)) errors.push('电子邮箱格式不正确');
        if (telephone && !isValidTelephone(telephone)) errors.push('联系电话需为11位有效手机号');
        if (newPass || currentPass) {
            if (!currentPass) errors.push('请输入当前密码');
            if (newPass && newPass.length < 8) errors.push('新密码长度至少8位');
            if (newPass !== confirmPass) errors.push('两次输入的密码不一致');
        }

        if (errors.length > 0) {
            showErrorToast(errors.join('\n'));
            return;
        }

        // 执行保存逻辑
        saveProfile();
    });

    // 发送AJAX请求保存个人信息
    function saveProfile() {
        saveBtn.disabled = true;
        saveBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';
        const teacher_id = document.getElementById('teacher_id').textContent;
        // alert(teacher_id);
        const formData = new FormData(profileForm);

        fetch(`/teacher/message/update/${teacher_id}`, {
            method: 'POST',
            body: formData,
            credentials: 'same-origin'
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('服务器响应错误');
            }
            return response.json();
        })
        .then(data => {
            // 根据后端返回状态显示消息
            if (data.status === 'success') {
                showSuccessToast(data.message || '个人信息已成功保存！');

                // passwordInputs.forEach(input => input.value = ''); // 清空密码框
                setTimeout(function() {
    window.location.href = "/teacher";
}, 1000); // 5000毫秒即5秒后刷新页面
            } else {
                showErrorToast(data.message || '保存失败，请重试');
            }
        })
        .catch(error => {
            console.error('保存失败:', error);
            showErrorToast('网络错误，请稍后重试');
        })
        .finally(() => {
            saveBtn.disabled = false;
            saveBtn.innerHTML = '<i class="fa fa-save mr-2"></i> 保存更改';
        });
    }

    // 密码显示/隐藏功能
    function initPasswordToggle(toggleBtn, inputId) {
        const input = document.getElementById(inputId);
        const icon = toggleBtn.querySelector('i');
        toggleBtn.addEventListener('click', () => {
            input.type = input.type === 'password' ? 'text' : 'password';
            icon.classList.toggle('fa-eye-slash');
            icon.classList.toggle('fa-eye');
        });
    }

    // 验证函数
    function isValidEmail(email) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); }
    function isValidTelephone(telephone) { return /^1[3-9]\d{9}$/.test(telephone); }

    // Toast提示功能
    function showErrorToast(message) { createToast('error', message); }
    function showSuccessToast(message) { createToast('success', message); }

    // 创建Toast元素
    function createToast(type, message) {
        const toast = document.createElement('div');
        toast.className = `toast fixed bottom-4 right-4 p-4 rounded-lg shadow-lg z-50 transition-all duration-300 transform ${
            type === 'error' ? 'bg-red-500 text-white' : 'bg-green-500 text-white'
        }`;
        toast.innerHTML = `
            <div class="flex items-center">
                <div class="mr-2">
                    ${type === 'error' ? '<i class="fa fa-exclamation-triangle"></i>' : '<i class="fa fa-check-circle"></i>'}
                </div>
                <div>${message}</div>
            </div>
        `;

        // 添加动画效果
        toast.style.opacity = '0';
        toast.style.transform = 'translateY(20px)';

        document.body.appendChild(toast);

        // 触发动画
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateY(0)';
        }, 10);

        // 自动隐藏
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateY(20px)';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }
});